package com.uchengwang.ui.cm_ui.cycle.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.BaseWhitTitleNoBackActivity;
import com.uchengwang.ui.cm_ui.cycle.bean.H5MapLocationBean;
import com.uchengwang.ui.cm_ui.cycle.bean.SetupMenusBean;
import com.uchengwang.ui.cm_ui.cycle.bridge.WebViewJsHandler;
import com.uchengwang.ui.cm_ui.release.ui.ChooseVideoActivity;
import com.uchengwang.ui.cm_ui.release.ui.ReleaseActActivity;
import com.uchengwang.ui.cm_ui.release.ui.ReleaseRoomMeetActivity;
import com.uchengwang.ui.cm_ui.release.ui.ReleaseVoteActivity;
import com.uchengwang.ui.cm_ui.ucity.ui.ReleaseDynamicActivity;
import com.uchengwang.ui.cm_ui.uu.bean.ChooseItemBean;
import com.uchengwang.ui.listener.PermissionsListener;
import com.uchengwang.ui.self.jsbridge.BridgeWebView;
import com.uchengwang.ui.self.jsbridge.CallBackFunction;
import com.uchengwang.ui.self.jsbridge.DefaultHandler;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.MapManager;
import com.uchengwang.ui.utils.MoreOperateUtils;
import com.uchengwang.ui.utils.NetwotkUtil;
import com.uchengwang.ui.utils.PermissionUtils;
import com.uchengwang.ui.utils.PopupUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by U城网 on 2018/2/27.
 * 加载社圈的网页
 */

public class LoadCycleWebHtmlActivity extends BaseWhitTitleNoBackActivity implements View.OnClickListener{

    private BridgeWebView bridgeWebView;
    private FrameLayout load_fl;
    private String url, urlTitle;//网址和网址标题
    private int type;//1社圈广场
    private int pubType;//1关注圈 2会场圈

    private WebViewJsHandler handler;

    private RelativeLayout load_bottom;
    private EditText bottom_edit;
    private Button bottom_bt;
    private CallBackFunction function;

    private boolean isHideRight, isFull;//是否隐藏右上角的操作图标  是否全屏填充
    private LinearLayout load_no_net;
    private ProgressBar load_progressBar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_load_cycle_web);
        url = getIntent().getStringExtra(BaseConfig.URL);
        type = getIntent().getIntExtra(BaseConfig.TYPE, -1);
        pubType = getIntent().getIntExtra(BaseConfig.PUB_TYPE, 0);
        Log.d("jjf", "加载的url=="+url);
        urlTitle = getIntent().getStringExtra(BaseConfig.URL_TITLE);
        isHideRight = getIntent().getBooleanExtra(BaseConfig.IS_HIDE_RIGHT, false);
        isFull = getIntent().getBooleanExtra(BaseConfig.IS_FULL, false);

        if (!TextUtils.isEmpty(url)){
            url = url.trim();
        }

        if (isFull){
            //全屏显示
            getRy().setVisibility(View.GONE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

        EventBus.getDefault().register(this);

        if (!TextUtils.isEmpty(urlTitle)){
            getRy().setTitle(urlTitle);
        }

        if (!isHideRight){
            if (pubType ==2){
                //会场显示创建
                getRy().setRightText("创建", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BaseConfig.isReFresh = true;//发布成功后不在重复打开此界面
                        startActivity(new Intent(LoadCycleWebHtmlActivity.this, ReleaseRoomMeetActivity.class));
                    }
                });
            }else {
                int resId = R.drawable.more_operate;
                if (pubType >0){
                    resId = R.drawable.rc_ext_tab_add;
                }

                getRy().setImageRight(resId, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (pubType >0){
                            final List<ChooseItemBean> chooseItemBeans = new ArrayList<>();
                            switch (pubType){
                                case 1://关注圈
                                    chooseItemBeans.add(new ChooseItemBean("享说", R.drawable.icon_main_speek, 0, R.color.ustudy_no_choose));
                                    chooseItemBeans.add(new ChooseItemBean("视频", R.drawable.icon_main_video, 0, R.color.ustudy_no_choose));
                                    chooseItemBeans.add(new ChooseItemBean("活动", R.drawable.icon_main_act, 0, R.color.ustudy_no_choose));
                                    chooseItemBeans.add(new ChooseItemBean("投票", R.drawable.icon_main_vote, 0, R.color.ustudy_no_choose));
                                    chooseItemBeans.add(new ChooseItemBean("文章", R.drawable.icon_main_vote, 0, R.color.ustudy_no_choose));

                                    break;
                            }

                            PopupUtils.getUtils().rgihtMoreWithIcon(LoadCycleWebHtmlActivity.this, titleBar, chooseItemBeans, R.drawable.shape_item_bg, new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    PopupUtils.getUtils().dismiss();
                                    Intent intent = null;
                                    switch (chooseItemBeans.get(i).getTitle()){
                                        case "享说":
                                            intent = new Intent(LoadCycleWebHtmlActivity.this, ReleaseDynamicActivity.class);
                                            break;
                                        case "视频":
                                            intent = new Intent(LoadCycleWebHtmlActivity.this, ChooseVideoActivity.class);
                                            break;
                                        case "活动":
                                            intent = new Intent(LoadCycleWebHtmlActivity.this, ReleaseActActivity.class);
                                            break;
                                        case "投票":
                                            intent = new Intent(LoadCycleWebHtmlActivity.this, ReleaseVoteActivity.class);
                                            break;
                                        case "文章":
                                            intent = new Intent(LoadCycleWebHtmlActivity.this, LoadCycleWebHtmlActivity.class);
                                            intent.putExtra(BaseConfig.IS_FULL, false);
                                            intent.putExtra(BaseConfig.IS_HIDE_RIGHT, true);
                                            intent.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL + "/article/prepare");
                                            break;
                                    }
                                    if (intent != null){
                                        BaseConfig.isReFresh = true;//发布成功后不在重复打开此界面
                                        startActivity(intent);
                                    }
                                }
                            });
                        }else {
                            SetupMenusBean setupMenusBean = handler.getSetupMenusBean();
                            MoreOperateUtils.getUtils().more(LoadCycleWebHtmlActivity.this, getRy(), setupMenusBean);
                        }
                    }
                });
            }

        }


        initView();
    }

    private void initView() {
        load_no_net = (LinearLayout) findViewById(R.id.load_no_net);
//        bridgeWebView = (BridgeWebView) findViewById(R.id.load_webView);
        load_fl = (FrameLayout) findViewById(R.id.load_fl);
        bridgeWebView = new BridgeWebView(this);

        load_progressBar = (ProgressBar) findViewById(R.id.load_progressBar);

        load_bottom = (RelativeLayout) findViewById(R.id.load_bottom);
        load_bottom.setOnClickListener(this);
        bottom_edit = (EditText) findViewById(R.id.bottom_edit);
        bottom_bt = (Button) findViewById(R.id.bottom_bt);
        bottom_bt.setOnClickListener(this);

        load_fl.addView(bridgeWebView);
        bridgeWebView.setDefaultHandler(new DefaultHandler());
        bridgeWebView.setWebChromeClient(new WebChromeClient());
        /**
         * js发送给按住消息   submitFromWeb 是js调用的方法名    安卓\返回给js
         */
//        LoadingUtils.getUtils().loading(this);

        handler = WebViewJsHandler.getHandler();
        handler.registerWebviewJsHandlers(this, bridgeWebView);

        bridgeWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    load_progressBar.setVisibility(View.GONE);
                } else {
                    if (load_progressBar.getVisibility() == View.GONE){
                        load_progressBar.setVisibility(View.VISIBLE);
                    }
                    load_progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

        });

        System.out.println("打开的新界面:"+handler);

        if (!NetwotkUtil.isConnectInternet()){
            load_no_net.setVisibility(View.VISIBLE);
            load_fl.setVisibility(View.GONE);
            load_progressBar.setVisibility(View.GONE);
        }else {
            bridgeWebView.loadUrl(url);
        }

    }

    /**
     * 刷新数据
     * */
    public void onEvent(String refresh) {
        if (!TextUtils.isEmpty(refresh) && refresh.equals(BaseConfig.WEB_SHARE_DELETE_SUCCESS)){
            bridgeWebView.reload();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (BaseConfig.isRelease || UChengApplication.isCycleDelete){
            bridgeWebView.reload();
            BaseConfig.isRelease = false;
            UChengApplication.isCycleDelete = false;
        }

    }

    @Override
    public void onBackPressed() {
        switch (type){
            case 1://社圈广场
                setResult(1, new Intent());
                break;
        }
        if (bridgeWebView.canGoBack()){
            bridgeWebView.goBack();
        }else {
            super.onBackPressed();
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.setSetupMenusBeanNull();

        handler.clearUrl();
        handler = null;

        if (bridgeWebView != null) {
//            bridgeWebView.clearCache(true);
            ViewParent parent = bridgeWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(bridgeWebView);
            }
            bridgeWebView.removeAllViews();
            bridgeWebView.destroy();
            bridgeWebView = null;

            load_fl.removeAllViews();
            load_fl = null;
        }

        MapManager.getMapManager().desLocation();
        EventBus.getDefault().unregister(this);



//        if(bridgeWebView != null){
//            bridgeWebView.removeAllViews();
//            bridgeWebView.destroy();
//
//            load_fl.removeAllViews();
//            load_fl = null;
//        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bottom_bt:
                String content = bottom_edit.getText().toString();
                if (!TextUtils.isEmpty(content)){
                    function.onCallBack(content);
                }
                bottom_edit.setText("");
                load_bottom.setVisibility(View.GONE);
                UCommonUtil.getUtil().hideSoftInput(this, bottom_edit);

                break;
            case R.id.load_bottom:
                load_bottom.setVisibility(View.GONE);
                UCommonUtil.getUtil().hideSoftInput(this, bottom_edit);
                break;
        }
    }

    //打开软键盘
    /**
     * @param data h5界面传过来的内容
     * */
    public void openEdit(CallBackFunction f, String data){
        if (load_bottom.getVisibility() ==View.GONE){
            function = f;
            load_bottom.setVisibility(View.VISIBLE);
            bottom_edit.requestFocus();
            if (!TextUtils.isEmpty(data)){
                bottom_edit.setHint(data);
            }else {
                bottom_edit.setHint("");
            }
            UCommonUtil.getUtil().showSoftInput(this, bottom_edit);
        }
    }

    //获取定位信息
    public void getLocation(final OnResultListener listener){
        final H5MapLocationBean locationBean = new H5MapLocationBean();
        PermissionUtils.getUtils().checkLocation(this, new PermissionsListener() {
            @Override
            public void onSuccess() {
                MapManager.getMapManager().startLocation(new AMapLocationListener() {
                    @Override
                    public void onLocationChanged(AMapLocation aMapLocation) {
                        Log.d("ucw", "定位="+aMapLocation.toString());

                        if (aMapLocation != null){
                            locationBean.setLatitude(aMapLocation.getLatitude());
                            locationBean.setLongitude(aMapLocation.getLongitude());
                            locationBean.setStatus(0);

                        }else {
                            locationBean.setStatus(1);
                            locationBean.setMsg("定位失败");
                        }

                        String json = JsonUtils.getManager().beanToString(locationBean);
                        listener.onResult(0, "", 0, json);
                    }
                });
            }

            @Override
            public void onFailed() {
                locationBean.setStatus(1);
                locationBean.setMsg("缺少定位权限");
                String json = JsonUtils.getManager().beanToString(locationBean);
                listener.onResult(0, "", 0, json);
                UCommonUtil.getUtil().showToast(LoadCycleWebHtmlActivity.this, "缺少定位权限");
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        MapManager.getMapManager().stopLocation();
    }
}
